export const getImageInfo = url => {
  const len = url.length
  const isMultiple = Array.isArray(url) && len > 1
  if (isMultiple) {
    const imageInfos = []
    return new Promise(resolve => {
      url.forEach((src, index) => {
        uni.getImageInfo({
          src,
          success: imageInfo => {
            imageInfos.push(imageInfo)
            if (index === len - 1) {
              resolve(imageInfos)
            }
          },
          fail: err => {
            imageInfos.push({})
            if (index === len - 1) {
              resolve(imageInfos)
            }
          }
        })
      })
    })
  } else {
    const src = Array.isArray(url) ? url[0] : url
    return new Promise((resolve, reject) => {
      uni.getImageInfo({
        src,
        success: imageInfo => {
          /**
           * errMsg: "getImageInfo:ok"
            height: 717
            orientation: "up"
            path: "http://tmp/XW3SJ3xxHwmA8bc5cc118d7758e862e16f13cd068918.jpg"
            type: "jpeg"
            width: 1600
           */
          resolve(imageInfo)
        },
        fail: err => {
          reject(err)
        }
      })
    })
  }
}

const widthRatio = 1
const QUALITY = 8
const isJpgFun = type => {
  console.log(type)
  return ['png', 'jpg', 'jpeg'].indexOf(type) > -1
}
// 微信图片压缩
export const compressImage = async sUrl => {
  try {
    const imageInfo = await getImageInfo(sUrl)
    // console.log(imageInfo)
    return new Promise((resolve, reject) => {
      const newFiles = []
      const oldFiles = Array.isArray(imageInfo) ? imageInfo.filter(image => 'width' in image) : [imageInfo]
      if (oldFiles.length) {
        oldFiles.forEach(image => {
          const isJpg = isJpgFun(image.type)
          if (isJpg) {
            const compressedWidth = image.width * widthRatio
            wx.compressImage({
              src: image.path, // 图片路径
              quality: QUALITY * 10, // 压缩质量
              compressedWidth,
              success: res => {
                // console.log(res)
                const file = {
                  type: 'image',
                  url: res.tempFilePath,
                  thumb: res.tempFilePath
                }
                newFiles.push(file)
                if (newFiles.length === oldFiles.length) {
                  resolve(newFiles)
                }
              },
              fail: err => {
                console.log(err)
                if (newFiles.length === oldFiles.length) {
                  resolve(newFiles)
                }
              }
            })
          }
        })
      }
    })
  } catch (err) {
    console.log(err)
    return Promise.resolve()
  }
}

function formatImage(res) {
  const files = res.files ? res.files : res.tempFiles
  return files.map(item => ({
    type: 'image',
    url: item.path,
    thumb: item.path,
    size: item.size,
    // #ifdef MP-ALIPAY
    fileType: item.fileType,
    // #endif
    // #ifdef H5
    name: item.name
    // #endif
  }))
}

function formatVideo(res) {
  return [
    {
      type: 'video',
      url: res.tempFilePath,
      thumb: res.tempVideoThumbPath,
      size: res.size,
      // #ifdef MP-ALIPAY
      width: res.width,
      height: res.height,
      duration: res.duration,
      // #endif
      // #ifdef H5
      name: res.name
      // #endif
    }
  ]
}

export const chooseImage = ({ count, capture }) => {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      count,
      sourceType: capture,
      success: res => {
        const formatRes = formatImage(res)
        resolve(formatRes)
      },
      fail: reject
    })
  })
}

export const chooseVideo = ({ capture }) => {
  return new Promise((resolve, reject) => {
    uni.chooseVideo({
      sourceType: capture,
      success: res => {
        const formatRes = formatVideo(res)
        resolve(formatRes)
      },
      fail: reject
    })
  })
}

export const uploadFile = options => {
  const { url, filePath, token, name, fileType } = options
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      fileType: fileType || 'image',
      url,
      name,
      filePath,
      header: {
        Authorization: 'Bearer ' + token
      },
      success: res => {
        const resData = JSON.parse(res.data)
        if (resData.code === 200) {
          resolve(resData?.url || '')
        } else {
          reject(resData.message)
        }
      },
      fail: res => reject(res)
    })
  })
}
